package com.gl.goods.base;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.pm.ActivityInfo;
import android.content.res.Resources;
import android.graphics.Color;
import android.os.Build;
import android.os.Bundle;
import android.text.LoginFilter;
import android.text.Selection;
import android.text.Spannable;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.inputmethod.InputMethodManager;
import android.widget.EditText;
import android.widget.LinearLayout;

import androidx.annotation.Nullable;
import androidx.annotation.StringRes;

import com.gl.goods.ui.login.activity.LoginActivity;
import com.gl.goods.ui.main.activity.MainActivity;
import com.gl.goods.R;
import com.gl.goods.widght.LoadingDialog;
import com.gl.goods.widght.LoadingLayout;
import com.gl.library.swipeLayout.SwipeBackActivity;
import com.gl.library.swipeLayout.SwipeBackLayout;
import com.gl.library.tool.RxSPTool;
import com.gl.library.utils.CommUtils;
import com.gl.library.utils.StringUtils;
import com.hjq.toast.ToastUtils;

import org.simple.eventbus.EventBus;

import butterknife.ButterKnife;
import butterknife.Unbinder;

public abstract class BaseActivity extends SwipeBackActivity implements View.OnClickListener {
    protected final String TAG = getClass().getSimpleName();
    protected LayoutInflater mInflater;
    public BaseActivity mActivitySelf;
    private Unbinder mBinder;
    private LinearLayout mLlRootLayout;
    private LoadingDialog mLoadingDialog;
    private LoadingLayout mLoadingLayout;
    public LinearLayout mTitleBar;
    public boolean isTitleVisibility = false;
    public TitleBuilder titleBuilder;
    private long lastClickTime;
    public int memberId;
    public String loginToken;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        // 设置布局文件之前调用
        onBeforeSetContentView();
        mInflater = getLayoutInflater();
        // 设置只竖屏显示
        setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_UNSPECIFIED);
        //全局控制所有activity的进出动画；
        overridePendingTransition(R.anim.anim_activity_right_in, R.anim.anim_activity_left_out_slow);
        setStatusBar(Color.WHITE);
        // 设置基础布局文件
        setContentView(R.layout.activity_base);
        // 初始化布局文件
        if (initLayout() != 0) {
            mLlRootLayout = (LinearLayout) findViewById(R.id.ll_root_layout);
            if (mLlRootLayout == null) return;
            View rootView = View.inflate(this, initLayout(), null);
            mLlRootLayout.addView(rootView, new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT));
        }
        ToastUtils.setView(R.layout.toast_craete);
        mTitleBar = findViewById(R.id.line_title_bar);
        titleBuilder = new TitleBuilder(this);
        titleBuilder.setLeftIco(R.mipmap.icon_back).setLeftIcoListening(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                finish();
            }
        });
        setTitleVisibility(isTitleVisibility);

        // 初始化加载数据布局
        mLoadingLayout = (LoadingLayout) findViewById(R.id.view_loading);

        // 错误页面的点击按钮操作
        mLoadingLayout.setOnActionPositiveListener(new LoadingLayout.OnActionPositiveListener() {
            @Override
            public void onActionPositive() {
                onActionPositiveClick();
            }
        });

        mLoadingLayout.setOnActionNegativeListener(new LoadingLayout.OnActionNegativeListener() {
            @Override
            public void onActionNegative() {
                onActionNegativeClick();

                /** 无网络重试 */
                getActivity().startActivity(getActivity().getIntent());
                showDataView();
                if (getActivity().getClass() != MainActivity.class) {
                    AppManager.getAppManager().finishActivity(getActivity());
                    BaseActivity baseActivity = (BaseActivity)getActivity();
                    baseActivity.superFinish();
                }
            }
        });

        mActivitySelf = this;
        if (MyApplication.getInstance().isLogin()){
            memberId = RxSPTool.getInt(mActivitySelf,"memberId");
            loginToken = RxSPTool.getString(mActivitySelf,"token");
        }else {
            memberId = 0;
            loginToken = "";
        }
        // 注册依赖注入对象
        mBinder = ButterKnife.bind(this);
        // 注册事件总线对象
        EventBus.getDefault().register(this);
        // 设置滑动关闭Activity可用方向
        setDragEdge(SwipeBackLayout.DragEdge.LEFT);

        AppManager.getAppManager().addActivity(this);

        // 无网络状况
        if (!CommUtils.isNetworkAvailable(this)) {
            showNoNetWorkView();
        }
        // 初始化视图
        initView(savedInstanceState);
        // 初始化数据
        initData();
    }

    protected void setTitleVisibility(boolean isTitleVisibility) {
        if (isTitleVisibility){
            mTitleBar.setVisibility(View.GONE);
        }else {
            mTitleBar.setVisibility(View.VISIBLE);
        }
    }

    public Activity getActivity() {
        return this;
    }

    /**
     * 当某些页面无法直接使用finish关闭时，使用此方法
     */
    public void superFinish() {
        super.finish();
        this.overridePendingTransition(R.anim.slide_right_in, R.anim.slide_right_out);
    }

    public void showDialogLoading(@StringRes int resId) {
        if (mLoadingDialog == null) {
            mLoadingDialog = new LoadingDialog(this, resId);
        }
        if (!mLoadingDialog.isShowing()) {
            mLoadingDialog.show();
        }
    }

    /**
     * [防止快速点击]
     *
     * @return
     */

    private boolean isFastClick() {
        boolean flag = false;

        long curClickTime = System.currentTimeMillis();
        if ((curClickTime - lastClickTime) >= 1000) {
            flag = true;
        }
        lastClickTime = curClickTime;
        return flag;
    }

    /** 设置遮罩显示时是否可以返回 */
    public void setCancelable(boolean cancelable) {
        mLoadingDialog.setCancelable(cancelable);
    }

    public void hideDialogLoading() {
        if (mLoadingDialog != null && mLoadingDialog.isShowing()) {
            mLoadingDialog.dismiss();
            mLoadingDialog = null;
        }
    }

    public void showDefaultNoData(String errMsg) {
        mLoadingLayout.setVisibility(View.VISIBLE);
        mLoadingLayout.setStatue(LoadingLayout.NO_DATA);
        if (StringUtils.isNotEmpty(errMsg)) {
            mLoadingLayout.setErrorInfo(errMsg);
        }
    }

    public void showDefaultNoData(String errMsg, int resId) {
        mLlRootLayout.setVisibility(View.GONE);
        mLoadingLayout.setVisibility(View.VISIBLE);
        mLoadingLayout.setStatue(LoadingLayout.NO_DATA);
        mLoadingLayout.setErrorInfo(errMsg, resId);
    }

    public void showDataView() {
        mLlRootLayout.setVisibility(View.VISIBLE);
        mLoadingLayout.setVisibility(View.GONE);
        mLoadingLayout.setStatue(LoadingLayout.GONE);
    }

    public void showNoNetWorkView() {
        mLoadingLayout.setErrorInfo("网络请求失败\n请检查您的网络", R.mipmap.net_error);
        mLlRootLayout.setVisibility(View.GONE);
        mLoadingLayout.setVisibility(View.VISIBLE);
        mLoadingLayout.setStatue(LoadingLayout.NO_NETWORK);
    }

    @Override
    protected void onResume() {
        super.onResume();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        ToastUtils.getToast().cancel();
        ToastUtils.show("");
        hideDialogLoading();
        // 注销事件总线对象
        EventBus.getDefault().unregister(this);
    }

    @Override
    public void startActivity(Intent intent) {
        super.startActivity(intent);
        this.overridePendingTransition(R.anim.slide_left_in, R.anim.slide_left_out);
    }

    @Override
    public void startActivityForResult(Intent intent, int requestCode) {
        super.startActivityForResult(intent, requestCode);
        this.overridePendingTransition(R.anim.slide_left_in, R.anim.slide_left_out);
    }

    @Override
    public void finish() {
        super.finish();
        this.overridePendingTransition(R.anim.slide_right_in, R.anim.slide_right_out);
    }


    @Override
    public void onBackPressed() {
        super.onBackPressed();
        this.overridePendingTransition(R.anim.slide_right_in, R.anim.slide_right_out);
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            finish();
        }
        return false;
    }

    //跳转Activity
    public void goTo(Class<? extends Activity> des) {
        Intent intent = new Intent();
        intent.setClass(this, des);
        startActivity(intent);
        overridePendingTransition(android.R.anim.fade_in, android.R.anim.fade_out);
    }

    public void goTo(Class<? extends Activity> des, Intent intent) {
        intent.setClass(this, des);
        startActivity(intent);
        overridePendingTransition(android.R.anim.fade_in, android.R.anim.fade_out);
    }

    //跳转Activity
    public void goToForResult(Class<? extends Activity> des, int requestCode) {
        Intent intent = new Intent();
        intent.setClass(this, des);
        startActivityForResult(intent, requestCode);
        overridePendingTransition(android.R.anim.fade_in, android.R.anim.fade_out);
    }

    /**
     * 隐藏软键盘
     */
    public static void hideSoftKeyBoard(Activity activity) {
        if (activity == null) {
            return;
        }
        InputMethodManager imm = (InputMethodManager) activity
                .getSystemService(Context.INPUT_METHOD_SERVICE);
        if (imm != null && imm.isActive()) {
            imm.hideSoftInputFromWindow(activity.getWindow().peekDecorView()
                    .getWindowToken(), 0);
        }
    }

    /**
     * 显示软键盘
     */
    public static void showSoftKeyBoard(Activity activity) {
        if (activity == null) {
            return;
        }
        InputMethodManager imm = (InputMethodManager) activity
                .getSystemService(Context.INPUT_METHOD_SERVICE);
        if (imm != null && imm.isActive()) {
            imm.toggleSoftInput(InputMethodManager.SHOW_FORCED, 0);
        }
    }

    /**
     * 重写 getResource 方法，防止系统字体影响
     */
    @Override
    public Resources getResources() {//禁止app字体大小跟随系统字体大小调节
        Resources resources = super.getResources();
        if (resources != null && resources.getConfiguration().fontScale != 1.0f) {
            android.content.res.Configuration configuration = resources.getConfiguration();
            configuration.fontScale = 1.0f;
            resources.updateConfiguration(configuration, resources.getDisplayMetrics());
        }
        return resources;
    }

    /** 将editView光标置于末尾 */
    public void setEditSelectionEnd(EditText editText){
        //切换后将EditText光标置于末尾
        CharSequence charSequence = editText.getText();
        if (charSequence instanceof Spannable) {
            Spannable spanText = (Spannable) charSequence;
            Selection.setSelection(spanText, charSequence.length());
        }
    }

    protected void onBeforeSetContentView() {
    }

    protected void onActionNegativeClick() {
    }

    protected void onActionPositiveClick() {
    }

    protected abstract int initLayout();

    protected abstract void initView(Bundle savedInstanceState);

    protected  void initData() {
    }

    public void widgetClick(View view){

    }

    @Override
    public void onClick(View view) {
        if (isFastClick()){
            widgetClick(view);
        }
    }

    protected void setStatusBar(int color) {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            getWindow().setStatusBarColor(color);//设置状态栏颜色
            getWindow().getDecorView().setSystemUiVisibility(View.SYSTEM_UI_FLAG_LIGHT_STATUS_BAR);
//            getWindow().getDecorView().setSystemUiVisibility(View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN | View.SYSTEM_UI_FLAG_LIGHT_STATUS_BAR);//实现状态栏图标和文字颜色为暗色
        }
    }
    /**
     * 判断Activity是否Destroy
     *
     * @param mActivity
     * @return
     */
    public static boolean isDestroy(Activity mActivity) {
        if (mActivity == null || mActivity.isFinishing() || (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1 && mActivity.isDestroyed())) {
            return true;
        } else {
            return false;
        }
    }

    /**
     *@description:进入登录页
     */
    public void enterLoginActivity() {
        Intent intent = new Intent(getActivity(), LoginActivity.class);
        startActivity(intent);
    }
}
